<?php

namespace App\Models\Panx;

use App\Models\Concerns\ScopeFilterable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class MaterialPurchase
 * @package App\Models\Panx
 *
 * @method self filterName($name)
 * @method self filterManufacturer($manufacturer)
 * @method self filterBuyer($buyer)
 */

class MaterialPurchase extends Model
{
    use ScopeFilterable;

    protected $table = 'material_purchases';
    protected $guarded = [];

    protected $casts = [
        'id' => 'int'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function material()
    {
        return $this->belongsTo(Material::class, 'material_id', 'id');
    }


    /**
     * @used-by filterName
     * @param Builder $query
     * @param $name
     * @return Builder
     */
    public function scopeFilterName(Builder $query, $name)
    {
        if (! $name) return $query;

        return $query->whereHas('material', function(Builder $query) use($name){
            return $query->where('name', 'like', '%'.$name.'%');
        });
    }

    /**
     * @used-by filterManufacturer
     * @param Builder $query
     * @param $manufacturer
     * @return Builder
     */
    public function scopeFilterManufacturer(Builder $query, $manufacturer)
    {
        if (! $manufacturer) return $query;

        return $query->whereHas('material', function(Builder $query) use($manufacturer){
            return $query->where('manufacturer', 'like', '%'.$manufacturer.'%');
        });
    }

    /**
     * @used-by filterBuyer
     * @param Builder $query
     * @param $buyer
     * @return Builder
     */
    public function scopeFilterBuyer(Builder $query, $buyer)
    {
        if (! $buyer) return $query;

        return $query->where('buyer', 'like', '%'.$buyer.'%');
    }
}
